/**
 * @description: el-dialog函数式弹窗
 * @param {object} component 需要渲染的组件
 * @param {object} props 需要渲染的组件参数
 * @param {object} modalProps el-dialog配置项
 * @return {object}
 */
import { ElDialog, ElButton } from 'element-plus'

export default function renderDialog2(options) {
  return new Promise((resolve) => {
    const node = document.createElement('div')
    document.body.appendChild(node)

    let isClosed = false

    const app = createApp({
      setup() {
        const visible = ref(true)
        const instance = ref(null)

        const close = () => {
          if (isClosed) return

          isClosed = true
          visible.value = false
          setTimeout(() => {
            if (document.body.contains(node)) {
              app.unmount()
              document.body.removeChild(node)
            }
          }, 300)
        }

        // 处理自定义组件的事件
        const handleEvent = (payload) => {
          resolve(payload)
          close()
        }

        // 默认底部按钮
        const defaultFooter = () =>
          h('div', { class: 'dialog-footer' }, [
            h(
              ElButton,
              {
                onClick: close,
              },
              '取消',
            ),
            h(
              ElButton,
              {
                type: 'primary',
                onClick: handleEvent,
              },
              '确定',
            ),
          ])

        return () =>
          h(
            ElDialog,
            {
              ...options?.modalProps,
              modelValue: visible.value,
              'onUpdate:modelValue': (value) => (visible.value = value),
              onClose: close, // 监听弹窗关闭事件
            },
            {
              default: () =>
                h(options?.component, {
                  ref: instance,
                  ...options?.props,
                  on: {
                    ...options?.listeners,
                    customEvent: handleEvent, // 监听自定义组件的事件
                  },
                }),
              footer: options.footer ? options.footer : defaultFooter,
            },
          )
      },
    })

    app.use(ElDialog)
    app.mount(node)

    return app
  })
}
